//
//  SAPrintReturn.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/6/30.
//

#import "SAPrintReturn.h"
#import "SASalesInvoiceDetailModel.h"
#import "NSString+FintCommon.h"
#import "SACommoditySpecialFeesModel.h"

@interface SAPrintReturn ()

@property (nonatomic, strong) NSArray *typographyArr;
@property (nonatomic, assign) BOOL isHongKong;

@end

@implementation SAPrintReturn

+ (void)printWithTotalData:(SASalesInvoiceDetailModel *)model printSuccessBlock:(SAPrintSuccessBlock)printSuccessBlock {
        
     static BOOL isFirst = YES;
        
    SAPrintReturn *this = [[SAPrintReturn alloc] init];
    this.detailModel = model;
    this.userInfoModel = [SAValueManger shareInStance].userInfo;
    SACommoditySpecialFeesModel *hkSymbol = [SAOverallSetting shareInstance].hkSymbol;
    this.isHongKong = NO;
    if ([hkSymbol.value isEqualToString:@"1"]) {
        this.isHongKong = YES;
    }
    
    SACommoditySpecialFeesModel *ticketLayoutAttribute = [SAOverallSetting shareInstance].ticketLayoutAttribute;
    NSArray *arr = [ticketLayoutAttribute.value componentsSeparatedByString:@","];
    if (arr.count < 18) {
        arr = [NSArray arrayWithObjects:@"0", @"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",nil];
    }
    this.typographyArr = arr;
    
        if (this.overallSetting.printerSetting.printCopies == 0) {
            return;// 当前设置为：不打印
        }
        
        [this printStoreName];// 打印店铺名称
        [this printLineFeed];// 打印换行
        [this printHeader];// 打印头部
        [this printSku];// 打印sku数据
        [this printTotal];// 打印合计值（销售、退货、应收、实收、欠款、余款等）
        [this printBottom];// 打印底部（备足、银行卡信息、电话、地址、提示、操作人、公司名称）
        //
        [this printLineFeed];// 打印换行
        [this printLineFeed];// 打印换行
        [this printLineFeed];// 打印换行
        [this printLineFeed];// 打印换行
        [this printPaperCut];// 打印剪纸
    
    dispatch_async(dispatch_queue_create("print", DISPATCH_QUEUE_CONCURRENT), ^{
        for (NSInteger i = 0; i < this.overallSetting.printerSetting.printCopies; i++) {
            [[BluetoothManager sharedInstance] writeToPeripheralWithData:this.writeData success:^{
                NSLog(@"退货订单打印：写入成功");
                if (isFirst) {
                    isFirst = NO;
                    if (printSuccessBlock) {
                        printSuccessBlock();
                    }
                }
            } failure:^(NSString * _Nonnull errorMessage) {
                NSLog(@"退货订单打印：写入失败：%@",errorMessage);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [Prompt popPromptViewWithMsg:errorMessage duration:2];
                });
            }];
            [NSThread sleepForTimeInterval:3];
        }
    });
}

// 打印店铺名称
- (void)printStoreName {
    NSString *storeName = self.userInfoModel.storeName;
    NSData *data = [self.escPrinter printCenterText2:storeName font:(PrinterPrintTextFontMiddle)];;
    [self.writeData appendData:data];
}
// 打印：订单信息
- (void)printReceiptTypeTitle {
    
}

// 打印头部
- (void)printHeader {
    
    NSString *str1 = [NSString stringWithFormat:@"订单:%@",self.detailModel.saleOrderNo];
    NSString *typeStr = @"退货单";
    NSData *data1 = [self.escPrinter printLeftText:str1 rightText:typeStr font:(PrinterPrintTextFontSmall)];
    [self.writeData appendData:data1];
    
    NSString *str2 = [NSString stringWithFormat:@"日期:%@",self.detailModel.createTime];
    NSData *data2 = [self.escPrinter printText:str2 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
    [self.writeData appendData:data2];
    
    if ([self.typographyArr[0] isEqualToString:@"0"]) { //0 显示会员信息
        NSString *str3 = @"";
        if (self.detailModel.memberName.length > 0) {
            if (self.detailModel.memberLevelStr.length > 0) {
                str3 = [NSString stringWithFormat:@"会员:%@(%@)",self.detailModel.memberName,self.detailModel.memberLevelStr];
            }else {
                str3 = [NSString stringWithFormat:@"会员:%@",self.detailModel.memberName];
            }
        }else {
            str3 = @"会员:散客";
        }
        NSData *data3 = [self.escPrinter printText:str3 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
        [self.writeData appendData:data3];
    }
    
    if (self.detailModel.memberName.length == 0) {
        return; //散客没有以下信息
    }
    
    if ([self.typographyArr[1] isEqualToString:@"1"]) { //1 手机
        NSString *str4 = @"";
        if (self.detailModel.mobile.length > 0) {
            str4 = [NSString stringWithFormat:@"手机:%@",[self.detailModel.mobile securityIphoneNumString]];
        }else {
            str4 = @"手机:";
        }
        NSData *data4 = [self.escPrinter printText:str4 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
        [self.writeData appendData:data4];
    }
}

// 打印sku数据
- (void)printSku {
    
    SAOverallSetting *overallSetting = [SAOverallSetting shareInstance];
    NSInteger printerByteWidth = 48;
    if ([overallSetting.printSize.value isEqualToString:@"0"]) {
        printerByteWidth = 42;
    }
    
    // 1-一组颜色尺码打一行
    SAPrintSkuColorSizeLine *printSku = [[SAPrintSkuColorSizeLine alloc] init];
    if ([overallSetting.printSize.value isEqualToString:@"0"]) {
        if ([self.typographyArr[16] isEqualToString:@"16"]) {
            NSArray *printSkuStrArray = [printSku printSkuColorSizeLineWithProductSkuArray2:self.detailModel.productList printerByteWidth:printerByteWidth];
            for (NSData *data in printSkuStrArray) {
                    [self.writeData appendData:data];
            }
        }else {
            NSArray *printSkuStrArray = [printSku printSkuColorSizeLineWithProductSkuArray4:self.detailModel.productList printerByteWidth:printerByteWidth];
            for (NSData *data in printSkuStrArray) {
                    [self.writeData appendData:data];
            }
        }
    }else {
        if ([self.typographyArr[16] isEqualToString:@"16"]) {
            NSArray *printSkuStrArray = [printSku printSkuColorSizeLineWithProductSkuArray:self.detailModel.productList printerByteWidth:printerByteWidth];
            for (NSString *str in printSkuStrArray) {
                    NSData *data = [self.escPrinter printText:str font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
                    [self.writeData appendData:data];
            }
        }else {
            NSArray *printSkuStrArray = [printSku printSkuColorSizeLineWithProductSkuArray3:self.detailModel.productList printerByteWidth:printerByteWidth];
            for (NSString *str in printSkuStrArray) {
                    NSData *data = [self.escPrinter printText:str font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
                    [self.writeData appendData:data];
            }
        }
    }
}

// 打印合计值（销售、退货、应收、实收、欠款、余款等）
- (void)printTotal {
    
    NSString *str1 = [NSString stringWithFormat:@"退货: %zd款，%zd件，%0.2f元",self.detailModel.productList.count, [self.detailModel.count integerValue],[self.detailModel.actualPrice doubleValue]/100.f];
    if (self.isHongKong == YES) {
        str1 = [NSString stringWithFormat:@"退货: %zd款，%zd件，%0.2f港元",self.detailModel.productList.count, [self.detailModel.count integerValue],[self.detailModel.actualPrice doubleValue]/100.f];
    }
    [self printWordWrap:str1];
//    NSData *data1 = [self.escPrinter printText:str1 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
//    [self.writeData appendData:data1];
    
    if ([self.typographyArr[6] isEqualToString:@"6"]) { //4 --’号代表退
        // 退货标识
        NSString *str2 = [NSString stringWithFormat:@"\"-\"号代表退货"];
        NSData *data2 = [self.escPrinter printText:str2 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
        [self.writeData appendData:data2];
    }

//    if ([self.typographyArr[4] isEqualToString:@"4"] && self.detailModel.discountRate.length > 0) { //4 整单折扣
//        NSString *str3 = [NSString stringWithFormat:@"整单折扣:%0.2f%%",[self.detailModel.discountRate doubleValue]/100.f];
//        NSData *data3 = [self.escPrinter printText:str3 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
//        [self.writeData appendData:data3];
//    }
    
    if ([self.typographyArr[5] isEqualToString:@"5"]) { //5 抵扣金额
        if ([self.detailModel.deductPrice doubleValue] > 0) {
            NSString *str4 = [NSString stringWithFormat:@"抵扣金额:%0.2f元",[self.detailModel.deductPrice doubleValue]/100.f];
            if (self.isHongKong == YES) {
                str4 = [NSString stringWithFormat:@"抵扣金额:%0.2f港元",[self.detailModel.deductPrice doubleValue]/100.f];
            }
            NSData *data4 = [self.escPrinter printText:str4 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
            [self.writeData appendData:data4];
        }
    }

    [self printLineFeed];// 打印换行
    
    NSString *str5 = [NSString stringWithFormat:@"应退:%0.2f元",[self.detailModel.shouldPrice doubleValue]/100.f];
    if (self.isHongKong == YES) {
        str5 = [NSString stringWithFormat:@"应退:%0.2f港元",[self.detailModel.shouldPrice doubleValue]/100.f];
    }
    NSData *data5 = [self.escPrinter printText:str5 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
    [self.writeData appendData:data5];
    
    NSString *str6 = [NSString stringWithFormat:@"实退:%0.2f元",[self.detailModel.actualPrice doubleValue]/100.f];
    if (self.isHongKong == YES) {
        str6 = [NSString stringWithFormat:@"实退:%0.2f港元",[self.detailModel.actualPrice doubleValue]/100.f];
    }
    NSData *data6 = [self.escPrinter printText:str6 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
    [self.writeData appendData:data6];
    
    if ([self.typographyArr[7] isEqualToString:@"7"]) { //7 支付方式
        NSString *str8 = [self getDisplayPayWay:(id)self.detailModel.payList];// 支付方式
        [self printWordWrap:str8];
//        NSData *data8 = [self.escPrinter printText:str8 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
//        [self.writeData appendData:data8];
    }
    
    SAOverallSetting *overallSetting = [SAOverallSetting shareInstance];
    NSInteger printerByteWidth = 48;
    if ([overallSetting.printSize.value isEqualToString:@"0"]) {
        printerByteWidth = 32;
    }
    
    NSString *print = kPrint;
    if (print != nil && print.length > 7) {
        NSString *printName = [kPrint substringToIndex:7];
        // 二维码模块大小 1~16
        if ([printName isEqualToString:@"MHT-P58"]) {
            printerByteWidth = 42;
        }
    }
    
    NSString *partingLine = [NSString getPrintPartingLineWithByteWidth:printerByteWidth originX:0];
    NSData *data9 = [self.escPrinter printText:partingLine font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
    [self.writeData appendData:data9];
}

// 打印底部（备注、银行卡信息、电话、地址、提示、操作人、公司名称）
- (void)printBottom {
    
    if ([self.typographyArr[9] isEqualToString:@"9"]) { //9 操作人
        NSString *str1 = [NSString stringWithFormat:@"操作人: %@",self.detailModel.empName];
        NSData *data1 = [self.escPrinter printText:str1 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
        [self.writeData appendData:data1];
    }
    
    if ([self.typographyArr[10] isEqualToString:@"10"]) { //10 联系电话
        if (self.userInfoModel.storeInfo.contactPhone.length > 0) {
            NSString *str2 = [NSString stringWithFormat:@"联系电话: %@",self.userInfoModel.storeInfo.contactPhone];
            NSData *data2 = [self.escPrinter printText:str2 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
            [self.writeData appendData:data2];
        }
    }
    
    if ([self.typographyArr[11] isEqualToString:@"11"]) { //11 联系地址
        if (self.userInfoModel.storeInfo.address.length > 0) {
            NSString *str3 = [NSString stringWithFormat:@"联系地址: %@",self.userInfoModel.storeInfo.address];
            [self printWordWrap:str3];
//            NSData *data3 = [self.escPrinter printText:str3 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
//            [self.writeData appendData:data3];
        }
    }
    
    if ([self.typographyArr[12] isEqualToString:@"12"]) { //12 提醒
        NSString *str4 = @"*钱款、件数请当面点清，离店概不负责";
        if ([SAValueManger shareInStance].userInfo.storeInfo.warnDesc.length > 0) {
            str4 = [SAValueManger shareInStance].userInfo.storeInfo.warnDesc;
        }
        [self printWordWrap:str4];
//        NSData *data4 = [self.escPrinter printText:str4 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
//        [self.writeData appendData:data4];
    }
    
    // 换行
    [self printLineFeed];
    
    if ([self.typographyArr[15] isEqualToString:@"15"]) {
        NSData *data7 = [self.escPrinter printCenterText2:@"深圳市孚云信息科技有限公司" font:(PrinterPrintTextFontSmall)];
        [self.writeData appendData:data7];
        
        NSData *data5 = [self.escPrinter printCenterText2:@"衣点通服装管理系统" font:(PrinterPrintTextFontSmall)];
        [self.writeData appendData:data5];
        
        NSData *data6 = [self.escPrinter printCenterText2:@"全国客服热线电话:0755-27804689" font:(PrinterPrintTextFontSmall)];
        [self.writeData appendData:data6];
    }
}


// 打印分割线
- (void)printPartingLine {
    NSData *data = [self.escPrinter printPartingLine:0];
    [self.writeData appendData:data];
}
// 打印换行
- (void)printLineFeed {
    NSData *data = [self.escPrinter lineFeed];
    [self.writeData appendData:data];
}
// 打印剪纸
- (void)printPaperCut {
    NSData *data = [self.escPrinter paperCut];
    [self.writeData appendData:data];
}

-(void)printWordWrap:(NSString *)text {
    SAOverallSetting *overallSetting = [SAOverallSetting shareInstance];
    if ([overallSetting.printSize.value isEqualToString:@"0"]) {
        NSInteger len = [NSString getPrintTextByteTotalWithText:text font:NSStringFontSmall];
        if (len > 32) {
            NSString *newStr = [NSString stringWithFormat:@"%@",text];
            for (int i = 0; i < len; i= i + 32) {
                NSString *str = [newStr getSubStringWithByteWidthMax:32 font:NSStringFontSmall];
                newStr = [newStr substringFromIndex:str.length];
                NSData *data = [self.escPrinter printText:str font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
                [self.writeData appendData:data];
            }
        }else {
            NSData *data = [self.escPrinter printText:text font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
            [self.writeData appendData:data];
        }
    }else {
        NSData *data = [self.escPrinter printText:text font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
        [self.writeData appendData:data];
    }
}

@end
